#include "weatherwidget.h"
#include <QGroupBox>
#include <QFormLayout>
#include <QPainter>
#include <QPropertyAnimation>
#include <QMouseEvent>

WeatherWidget::WeatherWidget(QWidget *parent) : QWidget(parent),
  currentWeatherBox(nullptr),
  forecastBox(nullptr),
  minButton(nullptr),
  closeButton(nullptr)
{
    // 初始化城市映射（城市名:城市代码）
    cityMap["北京"] = "101010100";
    cityMap["上海"] = "101020100";
    cityMap["广州"] = "101280101";
    cityMap["深圳"] = "101280601";
    cityMap["成都"] = "101270101";

    setupUI();
    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(onReplyFinished(QNetworkReply*)));

    // 初始请求默认城市天气
    currentCityCode = cityMap["北京"];
    fetchWeather();

    // 设置窗口透明背景和无边框
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowFlags(Qt::FramelessWindowHint);

    // 应用全局科技风样式
    applyTechStyle();
}

void WeatherWidget::setupUI()
{
    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(15, 40, 15, 15);

    // 添加窗口控制按钮
    minButton = new QPushButton(this);
    closeButton = new QPushButton(this);

    // 使用系统图标保持一致性
    QPixmap minPix = style()->standardPixmap(QStyle::SP_TitleBarMinButton);
    QPixmap closePix = style()->standardPixmap(QStyle::SP_TitleBarCloseButton);

    minButton->setIcon(minPix);
    closeButton->setIcon(closePix);

    // 设置按钮位置
    int buttonSize = 25;
    minButton->setGeometry(width() - 2 * buttonSize - 10, 10, buttonSize, buttonSize);
    closeButton->setGeometry(width() - buttonSize - 10, 10, buttonSize, buttonSize);

    // 设置提示文本
    minButton->setToolTip("最小化");
    closeButton->setToolTip("关闭");

    // 连接信号槽
    connect(minButton, &QPushButton::clicked, this, &QWidget::showMinimized);
    connect(closeButton, &QPushButton::clicked, this, &QWidget::close);

    // 顶部控制区域
    QHBoxLayout *topLayout = new QHBoxLayout();
    cityComboBox = new QComboBox(this);
    cityComboBox->addItems(cityMap.keys());
    connect(cityComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(onCityChanged(int)));

    refreshButton = new QPushButton("刷新", this);
    connect(refreshButton, SIGNAL(clicked()), this, SLOT(fetchWeather()));

    topLayout->addWidget(cityComboBox);
    topLayout->addWidget(refreshButton);
    topLayout->addStretch();

    // 当前天气区域
    currentWeatherBox = new QGroupBox("当前天气", this);  // 使用成员变量
    QFormLayout *currentLayout = new QFormLayout(currentWeatherBox);

    cityLabel = new QLabel("--", this);
    tempLabel = new QLabel("--", this);
    weatherLabel = new QLabel("--", this);
    humidityLabel = new QLabel("--", this);
    windLabel = new QLabel("--", this);
    dateLabel = new QLabel("--", this);

    currentLayout->addRow("城市:", cityLabel);
    currentLayout->addRow("日期:", dateLabel);
    currentLayout->addRow("温度:", tempLabel);
    currentLayout->addRow("天气:", weatherLabel);
    currentLayout->addRow("湿度:", humidityLabel);
    currentLayout->addRow("风力:", windLabel);

    // 天气预报区域
    forecastBox = new QGroupBox("未来三天预报", this);  // 使用成员变量
    forecastLayout = new QGridLayout(forecastBox);
    forecastLayout->setHorizontalSpacing(15);
    forecastLayout->setVerticalSpacing(10);

    // 初始化预报标签（3天）
    for(int i = 0; i < 3; i++) {
        QLabel *fDateLabel = new QLabel("--", this);
        QLabel *fTempLabel = new QLabel("--", this);
        QLabel *fWeatherLabel = new QLabel("--", this);

        fDateLabel->setAlignment(Qt::AlignCenter);
        fTempLabel->setAlignment(Qt::AlignCenter);
        fWeatherLabel->setAlignment(Qt::AlignCenter);

        forecastDateLabels.append(fDateLabel);
        forecastTempLabels.append(fTempLabel);
        forecastWeatherLabels.append(fWeatherLabel);

        // 添加列标题
                if(i == 0) {
                    QLabel *dayHeader = new QLabel("日期", this);
                    QLabel *weatherHeader = new QLabel("天气", this);
                    QLabel *tempHeader = new QLabel("温度", this);

                    dayHeader->setAlignment(Qt::AlignCenter);
                    weatherHeader->setAlignment(Qt::AlignCenter);
                    tempHeader->setAlignment(Qt::AlignCenter);

                    forecastLayout->addWidget(dayHeader, 0, 1);
                    forecastLayout->addWidget(weatherHeader, 0, 2);
                    forecastLayout->addWidget(tempHeader, 0, 3);
                }

                // 添加行标题和内容
                QLabel *dayLabel = new QLabel(QString("第%1天").arg(i+1), this);
                dayLabel->setAlignment(Qt::AlignCenter);
                forecastLayout->addWidget(dayLabel, i+1, 0);
                forecastLayout->addWidget(fDateLabel, i+1, 1);
                forecastLayout->addWidget(fWeatherLabel, i+1, 2);
                forecastLayout->addWidget(fTempLabel, i+1, 3);
    }

    // 设置列宽比例
    forecastLayout->setColumnStretch(0, 1); // 第1列
    forecastLayout->setColumnStretch(1, 2); // 第2列
    forecastLayout->setColumnStretch(2, 2); // 第3列
    forecastLayout->setColumnStretch(3, 2); // 第4列

    // 组合布局
    mainLayout->addLayout(topLayout);
    mainLayout->addWidget(currentWeatherBox);
    mainLayout->addWidget(forecastBox);

    mainLayout->addStretch();
    setLayout(mainLayout);
    resize(600, 500);
    setWindowTitle("天气预报");

    int buttonSize_2 = 25;
      // 使用窗口宽度来正确定位按钮
      int buttonRightMargin = 15; // 右外边距
    minButton->setGeometry(width() - 2 * buttonSize_2 - buttonRightMargin, 10, buttonSize_2, buttonSize_2);
    closeButton->setGeometry(width() - buttonSize_2 - buttonRightMargin, 10, buttonSize_2, buttonSize_2);
}

void WeatherWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}

void WeatherWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    }
}

void WeatherWidget::onCityChanged(int index)
{
    QString cityName = cityComboBox->itemText(index);
    currentCityCode = cityMap[cityName];
    fetchWeather();
}

void WeatherWidget::fetchWeather()
{
    QString url = QString("http://t.weather.itboy.net/api/weather/city/%1")
                 .arg(currentCityCode);
    manager->get(QNetworkRequest(QUrl(url)));
}

void WeatherWidget::onReplyFinished(QNetworkReply *reply)
{
    if(reply->error() != QNetworkReply::NoError) {
        QMessageBox::warning(this, "错误", "网络请求失败: " + reply->errorString());
        reply->deleteLater();
        return;
    }

    QByteArray data = reply->readAll();
    reply->deleteLater();
    parseWeatherData(data);
}

void WeatherWidget::parseWeatherData(const QByteArray &data)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data, &error);

    if(error.error != QJsonParseError::NoError) {
        QMessageBox::warning(this, "错误", "JSON解析失败: " + error.errorString());
        return;
    }

    QJsonObject root = doc.object();
    if(root["status"].toInt() != 200) {
        QMessageBox::warning(this, "错误", "API返回状态异常");
        return;
    }

    // 更新当前天气
    QJsonObject cityInfo = root["cityInfo"].toObject();
    QJsonObject dataObj = root["data"].toObject();
    updateCurrentWeather(dataObj);

    // 更新预报
    QJsonArray forecast = dataObj["forecast"].toArray();
    updateForecast(forecast);
}

void WeatherWidget::updateCurrentWeather(const QJsonObject &data)
{
    cityLabel->setText(cityComboBox->currentText());
    dateLabel->setText(data["date"].toString());
    tempLabel->setText(QString("%1°C").arg(data["wendu"].toString()));
    weatherLabel->setText(data["forecast"].toArray()[0].toObject()["type"].toString());
    humidityLabel->setText(data["shidu"].toString());

    QJsonObject windObj = data["forecast"].toArray()[0].toObject();
    windLabel->setText(QString("%1 %2级")
                      .arg(windObj["fx"].toString())
                      .arg(windObj["fl"].toString().replace("级", "")));

    // 温度标签动画效果
    QPropertyAnimation *tempAnim = new QPropertyAnimation(tempLabel, "geometry");
    tempAnim->setDuration(800);
    tempAnim->setEasingCurve(QEasingCurve::OutBack);
    QRect startRect = tempLabel->geometry();
    tempAnim->setKeyValueAt(0, startRect.adjusted(0, -5, 0, -5));
    tempAnim->setKeyValueAt(0.5, startRect.adjusted(0, 5, 0, 5));
    tempAnim->setKeyValueAt(1, startRect);
    tempAnim->start(QAbstractAnimation::DeleteWhenStopped);
}

void WeatherWidget::updateForecast(const QJsonArray &forecast)
{
    for(int i = 0; i < 3 && i < forecast.size(); i++) {
        QJsonObject day = forecast[i].toObject();
        forecastDateLabels[i]->setText(day["date"].toString());
        forecastWeatherLabels[i]->setText(day["type"].toString());

        // 修正温度格式，移除重复的单位符号
        QString lowTemp = day["low"].toString().replace("低温 ", "").replace("℃", "");
        QString highTemp = day["high"].toString().replace("高温 ", "").replace("℃", "");
        forecastTempLabels[i]->setText(QString("%1/%2°C").arg(lowTemp).arg(highTemp));
    }
}

void WeatherWidget::applyTechStyle()
{
    // 主窗口样式
    setStyleSheet("WeatherWidget {"
                  "background-color: rgba(15, 21, 32, 220);"
                  "border: 2px solid #00aaff;"
                  "border-radius: 15px;"
                  "}");

    // 按钮科技感特效
    QString buttonStyle = "QPushButton {"
                         "background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
                         "stop:0 #0066cc, stop:1 #00ccff);"
                         "color: white;"
                         "font-weight: bold;"
                         "font-size: 12px;"
                         "border: 1px solid #00ffff;"
                         "border-radius: 8px;"
                         "padding: 8px;"
                         "min-width: 70px;"
                         "}"
                         "QPushButton:hover {"
                         "border: 2px solid #00ffff;"
                         "background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
                         "stop:0 #0088ff, stop:1 #00ffff);"
                         "}";
    refreshButton->setStyleSheet(buttonStyle);

    // 数据面板样式
    QString groupBoxStyle = "QGroupBox {"
                           "background-color: rgba(25, 35, 60, 180);"
                           "border: 1px solid #00aaff;"
                           "border-radius: 12px;"
                           "margin-top: 15px;"
                           "padding: 12px;"
                           "color: #00ffff;"
                           "font-weight: bold;"
                           "}"
                           "QGroupBox::title {"
                           "subcontrol-origin: margin;"
                           "left: 15px;"
                           "color: #00ffff;"
                           "}";

    if(currentWeatherBox) currentWeatherBox->setStyleSheet(groupBoxStyle);
    if(forecastBox) forecastBox->setStyleSheet(groupBoxStyle);

    // 标签样式
    QString labelStyle = "QLabel {"
                         "color: #e0e0ff;"
                         "font-size: 12px;"
                         "background: transparent;"
                         "}";
    QList<QLabel*> allLabels = findChildren<QLabel*>();
    for (QLabel* label : allLabels) {
        // 跳过温度标签（有特殊样式）
        if(label != tempLabel) {
            label->setStyleSheet(labelStyle);
        }
    }

    // 温度标签特殊样式
    tempLabel->setStyleSheet("QLabel {"
                             "color: #ff5500;"
                             "font-size: 28px;"
                             "font-weight: bold;"
                             "border-bottom: 2px dashed #00aaff;"
                             "}");

    // 下拉框样式
    cityComboBox->setStyleSheet("QComboBox {"
                               "background-color: rgba(255, 255, 255, 200);"  // 修改为白色半透明背景
                               "color: #000000;"                             // 文字改为黑色提高对比度
                               "font-weight: bold;"
                               "border: 1px solid #00aaff;"
                               "border-radius: 5px;"
                               "padding: 5px;"
                               "min-width: 120px;"
                               "}"
                               "QComboBox:hover {"
                               "background-color: rgba(255, 255, 255, 230);"  // 悬停时更亮的背景
                               "}"
                               "QComboBox::drop-down {"
                               "border: none;"
                               "}"
                               "QComboBox QAbstractItemView {"
                               "background-color: rgba(255, 255, 255, 200);"  // 下拉选项同样使用白色背景
                               "color: #000000;"                              // 黑色文字
                               "selection-background-color: #0066cc;"
                               "border: 1px solid #00aaff;"  // 添加青色边框
                               "}");

    // 预报表格标题样式
    QString headerStyle = "QLabel {"
                         "color: #00ffff;"
                         "font-weight: bold;"
                         "font-size: 13px;"
                         "border-bottom: 1px solid #00aaff;"
                         "padding-bottom: 5px;"
                         "}";

    // 应用标题样式
    QList<QLabel*> headers = forecastBox->findChildren<QLabel*>();
    for (QLabel* header : headers) {
        if(header->text() == "日期" || header->text() == "天气" || header->text() == "温度") {
            header->setStyleSheet(headerStyle);
        }
    }

    QString windowButtonStyle = R"(
        QPushButton {
            background-color: rgba(30, 40, 70, 180);
            border: 1px solid #00aaff;
            border-radius: 12px;
            padding: 2px;
        }
        QPushButton:hover {
            background-color: rgba(60, 80, 140, 220);
            border: 1px solid #00ffff;
        }
        QPushButton:pressed {
            background-color: rgba(90, 120, 200, 255);
        }
    )";

    minButton->setStyleSheet(windowButtonStyle);
    closeButton->setStyleSheet(windowButtonStyle);
}

void WeatherWidget::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制外发光边框
    QLinearGradient grad(0, 0, width(), 0);
    grad.setColorAt(0, QColor(0, 100, 200, 100));
    grad.setColorAt(1, QColor(0, 200, 255, 50));

    painter.setPen(QPen(QBrush(grad), 3));
    painter.drawRoundedRect(rect().adjusted(5, 5, -5, -5), 15, 15);

    // 绘制内发光
    painter.setPen(QPen(QColor(100, 200, 255, 80), 1));
    painter.drawRoundedRect(rect().adjusted(8, 8, -8, -8), 12, 12);
}

